/**
 * @program: yygh_parent
 * @ClassName OssServiceImpl
 * @description:
 * @author: zyw
 * @create: 2023-06-03 14:04
 * @Version 1.0
 **/
package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.yygh.oss.prop.OssConfig;
import com.atguigu.yygh.oss.service.OssService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OssConfig ossConfig;
    @Override
    public String upload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossConfig.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ossConfig.getKeyId();
        String accessKeySecret = ossConfig.getKeySecret();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossConfig.getBucketName();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String fileName = UUID.randomUUID().toString().replaceAll("-","")+file.getOriginalFilename();
        String time = new DateTime().toString("yyyy/MM/dd");
        fileName = time + "/" + fileName;
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    bucketName, fileName,
                    file.getInputStream());

            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return null;
        }
    }
}
 
